package com.handpay.zztong.hp;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.HttpEngine;
import com.handpay.framework.LuaTableUtil;
import com.handpay.framework.SecureManager;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.base.activity.ZZTongActivity;
import com.handpay.zztong.hp.bean.ActionBar;
import com.handpay.zztong.hp.paymentbill.model.Bill;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.config.ZZTConfig;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.paymentbill.activity.TransResultFailureActivity;
import com.handpay.zztong.hp.paymentbill.activity.TransResultSuccessActivity;
import com.handpay.zztong.hp.protocol.ATProtocolConstant;
import com.handpay.zztong.hp.protocol.BaseProtocolKey;
import com.handpay.zztong.hp.swiper.model.AccountTransfer;
import com.handpay.zztong.hp.trans.activity.VPOSActivity;
import com.handpay.zztong.hp.utils.AccountUtils;
import com.xys.libzxing.zxing.activity.CaptureActivity;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

import se.krka.kahlua.vm.LuaTable;

/**
 * @author yanglun E-mail:sunshine_yangl@sina.com
 * @version 2016-3-10 下午1:39:26
 */
public class WebPayWaitingResultActivity extends ZZTongActivity {

    private double amount;
    private int mPayType;
    public static final String billvalue = "bill";

    private ImageView mLoadingView;
    private View parent_view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setContentView(R.layout.activity_wating_result);
        super.onCreate(savedInstanceState);
        amount = this.getIntent().getDoubleExtra(VPOSActivity.Transfer_Amount_Key, 0d);
        mPayType = this.getIntent().getIntExtra(PAYTYPE, 0);
        parent_view=findViewById(R.id.parent_view);
        TextView shop_name_tv = (TextView) this.findViewById(R.id.shop_name_tv);
        goToCaptureActivity();
        TextView amount_tv = (TextView) this.findViewById(R.id.amount_tv);
        shop_name_tv.setText(AccountUtils.getShopName(this));
        this.mAction = getIntent().getByteExtra(ZZTongActivity.ACTION, ZZTongActivity.Action_Transfer1);
        amount_tv.setText(String.format("%s元", CommonUtils.formatMoney(amount / 100d)));
        mLoadingView = (ImageView) findViewById(R.id.iv_loading);
        Animation rotateAnimation = AnimationUtils.loadAnimation(this, R.anim.iv_rotate_anim);
        mLoadingView.setAnimation(rotateAnimation);
        mLoadingView.startAnimation(rotateAnimation);
    }

    @Override
    protected void onResume() {
        amount = this.getIntent().getDoubleExtra(VPOSActivity.Transfer_Amount_Key, 0d);
        super.onResume();
    }

    protected void goToCaptureActivity() {
        //在正扫返回的时候会有标题和默认布局显示
        myActionBar.setVisibility(View.INVISIBLE);
        parent_view.setVisibility(View.INVISIBLE);
        // 打开扫描界面扫描条形码或二维码
        Intent openCameraIntent = new Intent(this, CaptureActivity.class);
        openCameraIntent.putExtra(VPOSActivity.Transfer_Amount_Key, amount);
        openCameraIntent.putExtra(PAYTYPE, mPayType);
//        openCameraIntent.putExtra("isOpenWechatPayScan", getIntent().getBooleanExtra("isOpenWechatPayScan", false));
        startActivityForResult(openCameraIntent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            myActionBar.setVisibility(View.VISIBLE);
            parent_view.setVisibility(View.VISIBLE);
            String qrCode = data.getStringExtra("result");
            doWalletAccountTransfer(qrCode);
        } else {
            this.finish();
        }
    }

    @Override
    public ActionBar getActivityActionBar() {
        return new ActionBar(getString(R.string.wating_result_title), false);
    }

    /***
     * 扫描支付宝二维码
     *
     * @param qrCode 二维码内容
     */
    private void doWalletAccountTransfer(String qrCode) {
        Hashtable<String, String> params = new Hashtable<String, String>();
        params.put("amount", SecureManager.getInstance().des(BigDecimal.valueOf(amount).toPlainString(), 1, null));
        params.put("qrCode", SecureManager.getInstance().des(qrCode + "", 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.CHANNEL);
        params.put(ATProtocolConstant.CLIENTCHANNEL, ZZTConfig.UPDATE_CHANNEL);
//        params.put("tradeType", String.valueOf(mPayType));//扫码支付不传支付方式
        params.put("clientVersion", "v" + ClientEngine.VERSION);
        Double latitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LATITUDE, 0d);
        Double longtitude = (Double) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_LONGTITUDE, 0d);
        String address = (String) ClientEngine.getInstance().getGlobal(BaseProtocolKey.KEY_ADDRESS);
        HPLog.d(HPLog.SSX_TAG,"反扫交易获取的地理位置："+latitude.toString() + "," + longtitude.toString());
        params.put(BaseProtocolKey.KEY_LOCATION, latitude.toString() + "," + longtitude.toString());
        params.put(BaseProtocolKey.KEY_ADDRESS, address);
        params.put("requestTime", getTimeStimp());//时间戳防止网络请求出现重连机制
        doJsonPost(true,this, ZZTongActivity.Do_WalletAccountTransfer, AccountTransfer.class, params, false);
    }

    /***
     *
     * @return 获取时间戳
     */
    public static String getTimeStimp() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        return formatter.format(currentTime);
    }

    @Override
    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert, DialogInterface.OnClickListener on) {
        if (super.netJsonResponse(action, resp, showAlert, on)) return true;
        if (ZZTongActivity.Do_WalletAccountTransfer.equals(action)) {
            AccountTransfer accountTransfer = (AccountTransfer) resp;
            Bill bill = CommonUtils.generateBill(accountTransfer, Bill.APPCODE.TRANS);
            if (bill.getStatus() == 0 || bill.getStatus() == 2) {
                Intent intent = new Intent(this, TransResultFailureActivity.class);
                intent.putExtra(billvalue, bill);
                intent.putExtra(PAYTYPE, mPayType);//传递支付方式到结果页面
                startActivity(intent);
                this.setResult(0);
                this.finish();
            } else if (bill.getStatus() == 1) {
                Intent intent = new Intent(this, TransResultSuccessActivity.class);
                intent.putExtra(billvalue, bill);//传递账单到结果界面
                intent.putExtra(PAYTYPE, mPayType);////传递支付方式到结果页面
                intent.putExtra(ACTION, this.mAction);
                startActivity(intent);
                this.setResult(1);
                this.finish();
            }
        }
        return false;
    }

    @Override
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        closeProgressDialog();
        mLoadingView.clearAnimation();
        if (super.netResponse(action, resp, false)) {
            WebPayWaitingResultActivity.this.finish();
            return true;
        }
        if (ZZTongActivity.Do_WalletAccountTransfer.equals(action)) {
            byte data[] = (byte[]) resp.get(HttpEngine.Key_RespData);
            LuaTable luaTable = LuaTableUtil.stringToLuaTable(data, isDataCompile);
            Object objResponseCode = luaTable.rawget("responseCode");
            Object objErrMsg = luaTable.rawget("errMessage");
            if (null != objResponseCode && null != objErrMsg) {
                String errMessage = CommonUtils.objectToString(objErrMsg);
                showAlertDialog(WebPayWaitingResultActivity.this, getString(R.string.prompt), errMessage, false, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setResult(0);
                        finish();
                        dialog.dismiss();
                    }
                });
            } else {
                Bill bill = CommonUtils.generateBill(luaTable, Bill.APPCODE.TRANS);
                if (bill.getStatus() == 0 || bill.getStatus() == 2) {
                    Intent intent = new Intent(this, TransResultFailureActivity.class);
                    intent.putExtra(billvalue, bill);
                    intent.putExtra(PAYTYPE, mPayType);//传递支付方式到结果页面
                    startActivity(intent);
                    this.setResult(0);
                    this.finish();
                } else if (bill.getStatus() == 1) {
                    Intent intent = new Intent(this, TransResultSuccessActivity.class);
                    intent.putExtra(billvalue, bill);//传递账单到结果界面
                    intent.putExtra(PAYTYPE, mPayType);////传递支付方式到结果页面
                    intent.putExtra(ACTION, this.mAction);
                    startActivity(intent);
                    this.setResult(1);
                    this.finish();
                }
            }
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode != KeyEvent.KEYCODE_BACK && super.onKeyDown(keyCode, event);
    }
}
